package com.kcyu.sfhinvoice.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kcyu.sfhinvoice.config.MyException;
import com.kcyu.sfhinvoice.domain.*;
import com.kcyu.sfhinvoice.dto.WebPage;
import com.kcyu.sfhinvoice.service.*;
import com.kcyu.sfhinvoice.utils.LuckyColaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "发票管理")
@RequestMapping("/invoice")
public class InvoiceController {

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private InvoiceStructService invoiceStructService;

    @Autowired
    private CommonTemplateService commonTemplateService;

    @Autowired
    private FileService fileService;


    @PostMapping("addInvoice")
    @ApiOperation(value = "添加发票")
    @SaCheckRole(value = {"管理员", "公司文员"}, mode = SaMode.OR)
    public SaResult addInvoice(@RequestBody Invoice invoice) {
        Invoice invoice1 = invoiceService.addInvoice(invoice);
        return SaResult.data(invoice1);
    }

    @PostMapping("updateInvoice")
    @ApiOperation(value = "修改发票")
    public SaResult updateInvoice(@RequestBody Invoice invoice) {
        boolean b = invoiceService.updateById(invoice);
        return SaResult.data(b);
    }

    @PostMapping("removeInvoice")
    @ApiOperation(value = "删除发票")
    @SaCheckRole(value = {"管理员", "公司文员"}, mode = SaMode.OR)
    public SaResult removeInvoice(@RequestParam("id") String id) {
        boolean b = invoiceService.removeInvoice(id);
        return SaResult.data(b);
    }

    @PostMapping("page")
    @ApiOperation(value = "分页查询")
    public SaResult page(@RequestBody WebPage<Invoice> invoice) {
        return SaResult.data(invoiceService.page(invoice));
    }

    @PostMapping("getStatistic")
    @ApiOperation(value = "统计")
    public SaResult getStatistic(@RequestBody Invoice invoice) {
        Map statistic = invoiceService.getStatistic(invoice);
        return SaResult.data(statistic);
    }

    @PostMapping("getById")
    @ApiOperation(value = "根据id查询")
    public SaResult getById(@RequestParam("id") String id) {
        return SaResult.data(invoiceService.getById(id));
    }

    @PostMapping("changeAddedStatus")
    @ApiOperation(value = "修改发票状态-已添加")
    public SaResult changeAddedStatus(@RequestParam("id") String id) {
        return SaResult.data(invoiceService.changeAddedStatus(id));
    }

    @PostMapping("finishAddedStatus")
    @ApiOperation(value = "修改发票状态-已完成")
    public SaResult finishAddedStatus(@RequestParam("id") String id) {
        return SaResult.data(invoiceService.finishAddedStatus(id));
    }

    @PostMapping("addInvoiceTrack")
    @ApiOperation(value = "根据发票ID添加历史记录")
    public SaResult addInvoiceTrack(@RequestBody InvoiceTrack invoiceTrack) {
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        User user = new User();
        User user1 = user.selectById(loginIdAsInt);
        invoiceTrack.setUser(user1.getUsername());
        return SaResult.data(invoiceTrack.insert());
    }

    @PostMapping("getInvoiceTrackById")
    @ApiOperation(value = "根据发票ID获取历史记录")
    public SaResult getInvoiceTrackById(@RequestParam("id") String id) {
        return SaResult.data(invoiceService.getInvoiceTrackById(id));
    }

    @PostMapping("addCommonTemplate")
    @ApiOperation(value = "添加常用模板")
    public SaResult addCommonTemplate(@RequestBody CommonTemplate commonTemplate) {
        // 判断buyer是否已存在
        if (checkTemplateIsRepeat(commonTemplate))
            return SaResult.error("已存在" + commonTemplate.getBuyer() + "的模板");
        int insert = commonTemplateService.getBaseMapper().insert(commonTemplate);
        return SaResult.data(insert);
    }

    @PostMapping("listAllTemplate")
    @ApiOperation(value = "查询所有模板")
    public SaResult listAllTemplate(@RequestParam("seller") String seller) {
        QueryWrapper<CommonTemplate> wrapper = new QueryWrapper<>();
        wrapper.eq("seller", seller);
        return SaResult.data(commonTemplateService.getBaseMapper().selectList(wrapper));
    }

    @PostMapping("queryTemplate")
    @ApiOperation(value = "查询模板")
    public SaResult queryTemplate(@RequestBody CommonTemplate commonTemplate) {
        return SaResult.data(commonTemplateService.queryTemplate(commonTemplate));
    }

    @PostMapping("checkHasTemplate")
    @ApiOperation(value = "查询是否已有模板")
    public SaResult checkHasTemplate(@RequestParam("buyer") String buyer, @RequestParam("seller") String seller) {
        QueryWrapper<CommonTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CommonTemplate::getBuyer, buyer);
        queryWrapper.lambda().eq(CommonTemplate::getSeller, seller);
        CommonTemplate one = commonTemplateService.getOne(queryWrapper);
        if(one != null) {
            return SaResult.data(true);
        } else {
            return SaResult.data(false);
        }
    }

    @PostMapping("removeTemplate")
    @ApiOperation(value = "删除模板")
    public SaResult removeTemplate(@RequestParam("id") String id) {
        boolean b = commonTemplateService.removeById(id);
        return SaResult.data(b);
    }

    @PostMapping("saveOrUpdateTemplate")
    @ApiOperation(value = "保存或更新模板")
    public SaResult saveOrUpdateTemplate(@RequestBody CommonTemplate commonTemplate) {
//        if (checkTemplateIsRepeat(commonTemplate))
//            return SaResult.error("已存在" + commonTemplate.getBuyer() + "的模板");
        boolean b = commonTemplateService.saveOrUpdate(commonTemplate);
        return SaResult.data(b);
    }

    @PostMapping("saveComment")
    @ApiOperation(value = "保存评论")
    public SaResult saveComment(@RequestBody Comment comment) {
        int loginUserId = StpUtil.getLoginIdAsInt();
        User user = new User().selectById(loginUserId);
        comment.setUserId(loginUserId);
        comment.setUserName(user.getUsername());
        boolean insert = comment.insert();
        if(insert) {
            return SaResult.ok();
        } else {
            return SaResult.error();
        }
    }

    @PostMapping("deleteComment")
    @ApiOperation(value = "删除评论")
    public SaResult deleteComment(@RequestParam("id") Integer id) {
        Comment comment = new Comment().selectById(id);
        if (comment.getUserId() != StpUtil.getLoginIdAsInt()) {
           throw new MyException("不允许越权操作");
        } else {
            boolean b = comment.deleteById(id);
            if(b) {
                return SaResult.ok();
            } else {
                return SaResult.error();
            }
        }
    }

    @PostMapping("getComment")
    @ApiOperation(value = "获取评论")
    public SaResult getComment(@RequestParam("id") Integer id) {
        Comment comment = new Comment();
        List<Comment> invoices = comment.selectList(new QueryWrapper<Comment>().eq("invoice_id", id));
        return SaResult.data(invoices);
    }


    @Deprecated
    @PostMapping("ocrInvoice")
    @ApiOperation(value = "OCR识别发票")
    public SaResult ocrInvoice(@RequestBody String fileId) {
        FileDO file = fileService.getById(fileId);
        if (file == null) {
            return SaResult.error("文件不存在");
        }
        String filePath = file.getFilePath();
        LuckyColaUtils luckyColaUtils = new LuckyColaUtils();
        String invoiceDate = luckyColaUtils.getInvoiceDate(filePath);
        return SaResult.data(invoiceDate);
    }

    @PostMapping("getInvoiceStruct")
    @ApiOperation(value = "获取发票结构化数据")
    public SaResult getInvoiceStruct(@RequestParam("invoiceId") String invoiceId) {
        InvoiceStruct invoiceStruct = invoiceStructService.getInvoiceStruct(invoiceId);
        return SaResult.data(invoiceStruct);
    }

    private boolean checkTemplateIsRepeat(@RequestBody CommonTemplate commonTemplate) {
        QueryWrapper<CommonTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CommonTemplate::getBuyer, commonTemplate.getBuyer());
        queryWrapper.lambda().eq(CommonTemplate::getSeller, commonTemplate.getSeller());
        CommonTemplate one = commonTemplateService.getOne(queryWrapper);
        if(one != null) {
            return true;
        }
        return false;
    }

}
